import { FC } from "react";
import { Button, Form, Input, message, Space, Typography } from "antd";
import styles from "./index.module.scss";
import { UserAddOutlined } from "@ant-design/icons";
import { Link, useNavigate } from "react-router-dom";
import { LOGIN_PATHNAME } from "../../router";
import { useRequest } from "ahooks";
import { registerService } from "../../services/user";

const { Title } = Typography;

const Register: FC = () => {
  const nav = useNavigate();

  const { loading, run } = useRequest(
    async (values: { [key: string]: any }) =>
      await registerService(values.username, values.password, values.nickname),
    {
      manual: true,
      onSuccess() {
        message.success("注册成功");
        nav(`/login`);
      },
    }
  );

  const onFinished = (values: { [key: string]: any }) => {
    run(values);
  };

  return (
    <div className={styles.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserAddOutlined />
          </Title>
          <Title level={2}>注册新用户</Title>
        </Space>
      </div>
      <div>
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          style={{ width: "300px" }}
          onFinish={onFinished}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              { required: true, message: "用户名不能为空" },
              {
                type: "string",
                min: 5,
                max: 20,
                message: "字符长度在5-20之间",
              },
              { pattern: /^\w+$/, message: "只能是数字字母或下划线" },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "密码不能为空" }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="confirm"
            dependencies={["password"]}
            rules={[
              { required: true, message: "请确认密码" },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue("password") === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error("密码不一致"));
                },
              }),
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item label="昵称" name="nickname">
            <Input />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                注册
              </Button>
              <Link to={LOGIN_PATHNAME}>已有账号，去登录</Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Register;
